// pages/StudyCardRenew/StudyCardRenew.js
let app = getApp();
const httpUtils = require('../../utils/httpUtils.js');
let tool = require('../../utils/tool.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: "",
    amount: "",
    id: "",
    name: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      address: options.address,
      amount: options.amount,
      name: options.name,
      order_no:''
    })

  },
  tobuy: function () {
    let that = this
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    httpUtils.renewal({
      access_token: app.globalData.$TOKEN,
      card_id: this.data.id,
      openid: app.globalData.openid
    }).then((res) => {
      wx.hideLoading()
      // wx.navigateBack({
      //   delta: 1,
      // })
      this.setData({
        order_no: res.data.order_no
      })

      wx.requestPayment({
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.paySign,
        success: function (res) {
          //成功后调查询支付结果接口
          that.checkPayStatus();
        },
        fail: function (res) {
          // fail  
          if (res.errMsg == "requestPayment:fail cancel") {
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    });
  },
  /**
   * 获取支付结果状态
   */
  checkPayStatus: function () {
    let that = this;
    wx.showLoading({
      title: '获取支付结果...',
      mask: true
    })
    let paramArr = {
      access_token: app.globalData.$TOKEN,
      order_no: that.data.order_no
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "/api/Mallminiproject/orderinfo?sign=" + sign;
    let classPro = new Promise(
      function (resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );

    classPro.then(function (res) {
      let that = this
      console.log(JSON.stringify(res))
      if (res.data.code === 1) {
        //支付成功
        wx.hideLoading();
        payStatusTimes = 0;
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        })
        wx.navigateBack({
          delta: 1,
        })
      } else if (1082 == res.data.code) {
        //支付未完成，5s,15s,30s后再轮询查下结果
        if (payStatusTimes == 3) {
          payStatusTimes = 0;
          wx.showToast({
            title: res.data.info,
            icon: 'none',
            duration: 3000
          });
          return;
        }
        let waitTime = payStatusTimes == 0 ? 5000 : payStatusTimes == 1 ? 15000 : 30000;
        payStatusTimes++;
        setTimeout(function () {
          that.checkPayStatus()
        }, waitTime)

      } else {
        //失败或者其他g
        wx.hideLoading();
        payStatusTimes = 0;
        wx.showToast({
          title: res.data.info,
          icon: 'none',
          duration: 3000
        });
      }

    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})